package com.jiehoo.ooqi;

import java.io.Serializable;

/**
 * Query target, used in from part of QL, Field also need reference to it.
 */
public class From implements Serializable {
  private static final long serialVersionUID = -6528392983976667950L;

  public static final Class<DirectTable> DIRECT_TABLE_CLASS = DirectTable.class;

  private static final String DIRECT_TABLE_SEPERATOR = " ";

  /**
   * Model class type. If is direct table
   */
  private Class<?> target;

  /**
   * Alias for model class or table.
   */
  private String alias;

  public From() {
  }

  public From(Class<?> target, String alias) {
    this.target = target;
    this.alias = alias;
  }

  public From(String table, String alias) {
    setDirectTable(table, alias);
  }

  public Class<?> getTarget() {
    return target;
  }

  public void setTarget(Class<?> target) {
    this.target = target;
  }

  public String getAlias() {
    return alias;
  }

  public void setAlias(String alias) {
    this.alias = alias;
  }

  public boolean isDirectTable() {
    return target == DirectTable.class;
  }

  /**
   * Get alias only, useful when target is direct table, because alias will contains table name and alias.
   * @return real alias part only
   */
  public String getAliasOnly() {
    if (alias != null && alias.length() > 0) {
      if (isDirectTable()) {
        String[] s = getAlias().split(DIRECT_TABLE_SEPERATOR);
        if (s.length == 2) {
          return s[1];
        }

      } else {
        return alias;
      }
    }
    return "";
  }

  public void setDirectTable(String table, String alias) {
    this.target = DirectTable.class;
    if (alias != null && alias.length() > 0) {
      this.alias = table + DIRECT_TABLE_SEPERATOR + alias;
    } else {
      this.alias = table;
    }
  }

  public String toString() {
    if (isDirectTable()) {
      return alias;
    } else {
      if (alias != null && alias.length() > 0) {
        return target.getSimpleName() + " " + alias;
      } else {
        return target.getSimpleName();
      }
    }
  }

  class DirectTable {

  }
}
